<template>
  <div>
    <CDialog
      :visible="visible"
      :title="title"
      type="add"
      width="630px"
      @submit="handleSubmit"
      @cancel="handleCancel"
      @outerOpen="outerOpen"
    >
      <i-form
        v-loading="loading"
        ref="form"
        v-if="type !== 'batchDelete' && loaded"
        :items="items"
        :model="form"
        :rules="rules"
      >
        <template slot="import">
          <el-form-item label="导入名单" prop="batchData">
            <LoadFile v-model="batchData" ref="loadFile" />
          </el-form-item>
        </template>
        <template slot="unfreeze">
          <el-formItem>
            <el-button
              class="table-button-blue add-white-list-dlg__button"
              @click="handleSwitchShowInitialTime"
            >
              {{ this.showInitialTime ? '取消' : '添加' }}时长限制
            </el-button>
            <span style="color: red"
              >(若未添加时长限制规则，则可以无限时长使用)</span
            >
          </el-formItem>
        </template>
        <template
          slot="timeLimit"
          v-if="this.type === 'add' && this.showInitialTime"
        >
          <el-formItem label="时长限制" prop="initialTime">
            <div class="add-white-list-dlg__limit">
              <el-input
                class="add-white-list-dlg__limit__input"
                v-model="form.initialTime"
              />
              <span style="min-width: 70px; padding: 0 10px">小时</span>
              <el-select
                class="add-white-list-dlg__limit__select"
                v-model="form.date"
                placeholder="选择周期"
              >
                <el-option
                  v-for="item in circleOptions"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                >
                </el-option>
              </el-select>
            </div>
          </el-formItem>
        </template>
      </i-form>
      <div v-loading="loading" v-else-if="type === 'batchDelete' && loaded">
        <table class="add-white-list-dlg__table">
          <thead>
            <tr>
              <th>选择</th>
              <th>电站</th>
            </tr>
          </thead>
          <tbody>
            <tr v-for="item in stationList" :key="item.id + resetKey">
              <td>
                <input
                  type="radio"
                  @change="
                    () => {
                      handleRadioChange(item.id)
                    }
                  "
                  :checked="radioChecked(item.id)"
                />
              </td>
              <td>
                {{ item.stationName }}
              </td>
            </tr>
            <!-- <tr>
                <td>
                  <input type="radio" @change="() => {handleRadioChange('333')}" :checked="radioChecked('333')"/>
                </td>
                <td>
                  {{333}}
                </td>
              </tr> -->
          </tbody>
        </table>
        <!-- </el-radio-group> -->
      </div>
    </CDialog>
  </div>
</template>
<script>
import CDialog from '@/components/CDialog'
import LoadFile from '@/components/LoadFile'
import formValidate, { validateMap } from '@/utils/validate'
import { cloneDeep } from 'lodash'
import {
  listFreeStation,
  listInternalStation,
  addFreeListInfo,
  addInternalListInfo,
  batchAddFreeListInfo,
  batchAddInternalListInfo,
  batchDeleteFreeListInfo,
  batchDeleteInternalListInfo,
} from '@/api/user'

import _ from 'lodash'

import { exportExcel } from '@/utils'

const circle = {
  1: '每天',
  2: '每周',
  3: '每月',
  4: '每年',
}

const circleErrMes = {
  1: 24,
  2: 168,
  3: 744,
  4: 8784,
}

const tabsName = {
  INNER: 0, // 内部名单
  FREE: 1, // 免费名单
}

const dateTypeMap = {
  1: '每天',
  2: '每周',
  3: '每月',
  4: '每年',
}

export default {
  name: 'AddWhiteListDlg',
  components: { CDialog, LoadFile },
  props: {
    visible: {
      required: true,
      type: Boolean,
    },
    type: {
      required: true,
      type: String,
    },
    listType: {
      required: true,
      type: String,
    },
  },
  mounted() {
    if (this.type === 'add') {
      this.initialAdd()
    } else if (this.type === 'batchAdd') {
      this.initialBatchAdd()
    } else if (this.type === 'batchDelete') {
      this.initialBatchDelete()
    }

    let handler = () => {}

    if (this.listType == tabsName.INNER) {
      handler = listInternalStation
    } else {
      handler = listFreeStation
    }

    this.loading = true

    handler()
      .then((res) => {
        let list = []
        if (!Array.isArray(res)) return

        res.forEach((item) => {
          list.push({
            label: item.stationName,
            value: item.id,
          })
        })

        if (list.length > 0) {
          this.checked = list[0].value
        }

        this.stationList = res
        let index = this.items.findIndex((item) => item.value === 'stationId')
        if (index < 0) return

        this.$set(this.items, index, {
          ...this.items[index],
          options: list,
        })

        this.loaded = true
      })
      .catch((err) => {
        console.log(err)
      })
      .finally(() => {
        this.loading = false
      })
  },
  data() {
    return {
      circleOptions: Object.keys(circle).map((item) => {
        return {
          label: circle[item],
          value: item,
        }
      }),
      checkedId: '',
      resetKey: 1,
      stationList: [],
      stationName: '',
      title: '',
      loading: false,
      loaded: false,
      batchData: [],
      checked: '',
      showInitialTime: false,
      items: [
        {
          label: '适用电站',
          placeholder: '请选择电站',
          type: 'select',
          options: [],
          value: 'stationId',
          required: true,
          clearable: true,
        },
        {
          label: '姓名',
          placeholder: '请输入姓名',
          type: 'text',
          value: 'userName',
          required: true,
          clearable: true,
          ifRender: () => {
            return this.type === 'add'
          },
        },
        {
          label: '手机号',
          type: 'text',
          placeholder: '请输入手机号',
          value: 'mobile',
          required: true,
          clearable: true,
          ifRender: () => {
            return this.type === 'add'
          },
        },
        {
          slot: 'unfreeze',
          ifRender: () => {
            return this.type === 'add'
          },
        },
        {
          slot: 'timeLimit',
          // ifRender: () => {
          //   return this.type === 'add' && this.showInitialTime
          // },
        },
        {
          slot: 'import',
          ifRender: () => {
            return this.type === 'batchAdd'
          },
        },
      ],
      form: {
        initialTime: '',
        date: '1',
      },
      batchAddRules: {
        batchData: [
          {
            validator: (rules, value, callback) => {
              if (!Array.isArray(this.batchData) || this.batchData.length < 1) {
                callback(new Error('请上传正确的批量赠送表格'))
              } else {
                callback()
              }
            },
          },
        ],
      },
      addRules: {
        userName: [{ validator: formValidate('validateUserName') }],
        mobile: [{ validator: formValidate('validateMobile') }],
      },
      rules: {},
    }
  },
  methods: {
    radioChecked(val) {
      return this.checked === val
    },
    handleRadioChange(val) {
      console.log(val)
      this.checked = val
    },
    initialAdd() {
      this.title = '添加'
      this.rules = cloneDeep(this.addRules)
    },
    initialBatchAdd() {
      this.title = '批量添加'
      this.rules = cloneDeep(this.batchAddRules)
    },
    initialBatchDelete() {
      this.title = '批量删除'
    },
    handleSwitchShowInitialTime() {
      this.showInitialTime = !this.showInitialTime
      if (this.showInitialTime) {
        this.$set(this.rules, 'initialTime', [
          {
            required: true,
            message: '请输入小时',
          },
          {
            validator: formValidate('validatePositiveInteger'),
          },
          {
            validator: (rules, value, callback) => {
              if (!this.form.initialTime || this.form.initialTime === '') {
                callback(new Error('请输入小时!'))
              } else if (
                this.form.initialTime < 1 ||
                this.form.initialTime > circleErrMes[this.form.date]
              ) {
                callback(
                  new Error(
                    `请输入1-${circleErrMes[this.form.date]}之间的整数!`
                  )
                )
              } else {
                callback()
              }
            },
          },
        ])
      } else {
        this.$set(this.rules, 'initialTime', [])
      }

      this.$forceUpdate()
    },
    handleSubmit() {
      if (this.$refs.form) {
        this.$refs.form.validate((valid) => {
          if (!valid) return
          if (this.type === 'add') this.handleAdd()
          if (this.type === 'batchAdd') this.handleBatchAdd()
        })
      }
      if (this.type === 'batchDelete') this.handleBatchDelete()
    },
    handleAdd() {
      let handler = () => {}

      if (this.listType == tabsName.INNER) {
        handler = addInternalListInfo
      } else {
        handler = addFreeListInfo
      }

      if (!this.showInitialTime) {
        delete this.form.date
        delete this.form.initialTime
      }

      this.loading = true
      handler(this.form).then(
        () => {
          this.loading = false
          this.$message({
            showClose: true,
            message: '添加成功！',
            type: 'success',
          })

          this.$emit('update:visible', false)
          this.$emit('refreshTable')
        },
        () => {
          this.loading = false
        }
      )
    },
    handleBatchAdd() {
      let handler = () => {}

      if (this.listType == tabsName.INNER) {
        handler = batchAddInternalListInfo
      } else {
        handler = batchAddFreeListInfo
      }

      if (!this.showInitialTime) {
        delete this.form.date
        delete this.form.initialTime
      }

      let arr = this.batchData

      let whiteListInfos = []

      for (var i = 0; i < arr.length; i++) {
        arr[i].mobile = arr[i]['手机号']
        arr[i].userName = arr[i]['姓名']
        arr[i].timeLimit = arr[i]['时长限制(h)']
        arr[i].durationPeriod = arr[i]['周期限制']
        if (!arr[i].userName || !arr[i].mobile) {
          this.$message({
            showClose: true,
            message: '导入失败手机号或者用户名为空',
            type: 'warning',
          })

          whiteListInfos = []
          break
        }
        if (!validateMap.validateMobile.reg.test(arr[i].mobile)) {
          this.$message({
            showClose: true,
            message: '导入失败手机号码格式不正确',
            type: 'warning',
          })

          whiteListInfos = []
          break
        }
        if (!validateMap.validateUserName.reg.test(arr[i].userName)) {
          this.$message({
            showClose: true,
            message: '导入失败姓名应为中文、英文字母',
            type: 'warning',
          })

          whiteListInfos = []
          break
        }
        if (arr[i].userName.length > 8) {
          this.$message({
            showClose: true,
            message: '导入失败姓名长度不能超过8个字符',
            type: 'warning',
          })

          whiteListInfos = []
          break
        }

        if (
          (!arr[i].timeLimit && arr[i].durationPeriod) ||
          (arr[i].timeLimit && !arr[i].durationPeriod)
        ) {
          this.$message({
            showClose: true,
            message: '导入时长限制和周期限制需一一对应',
            type: 'warning',
          })

          whiteListInfos = []
          break
        }

        var obj = {}

        if (arr[i].mobile && arr[i].userName) {
          obj = {
            mobile: arr[i].mobile,
            userName: arr[i].userName,
          }
        }

        if (arr[i].timeLimit && arr[i].durationPeriod) {
          obj.initialTime = JSON.parse(arr[i].timeLimit)
          obj.date = JSON.parse(
            _.findKey(dateTypeMap, function (val) {
              return arr[i].durationPeriod == val
            })
          )
        }

        whiteListInfos.push(obj)
      }

      if (whiteListInfos.length <= 0) {
        this.$message({
          message: '数据导入失败',
          type: 'error',
          offset: 60,
        })
        this.$refs.loadFile.onRemove()
        return
      }

      handler({
        ...this.form,
        whiteListInfos,
      })
        .then((res) => {
          this.$message({
            showClose: true,
            message:
              (this.listType == tabsName.INNER
                ? '内部充电名单导入失败表'
                : '免费充电名单导入失败表') + '已导出',
            type: 'success',
          })
          exportExcel(
            res,
            this.listType == tabsName.INNER
              ? '内部充电名单导入失败表'
              : '免费充电名单导入失败表'
          )
        })
        .catch(() => {
          this.$refs.loadFile.onRemove()
        })
        .finally(() => {
          this.$emit('update:visible', false)
          this.$emit('refreshTable')
        })
    },
    handleBatchDelete() {
      if (!this.checked || this.checked === '') return

      let handler = () => {}
      if (this.listType == tabsName.INNER) {
        handler = batchDeleteInternalListInfo
      } else {
        handler = batchDeleteFreeListInfo
      }

      handler({
        stationId: this.checked,
      })
        .then(() => {
          this.$message({
            showClose: true,
            type: '批量删除成功！',
            message: '删除成功',
          })

          this.$emit('update:visible', false)
          this.$emit('refreshTable')
        })
        .catch((err) => {
          console.log(err)
        })
    },
    handleCancel() {
      this.$emit('update:visible', false)
    },
    outerOpen() {},
  },
}
</script>
<style lang="scss">
.add-white-list-dlg__limit {
  display: flex;
  .add-white-list-dlg__limit__input {
    .el-input {
      width: 80px;
    }
  }
}
</style>
<style lang="scss" scoped>
.add-white-list-dlg__button {
  height: 36px;
  border-radius: 4px;
}

.add-white-list-dlg__radio {
  display: flex;
}

.add-white-list-dlg__table {
  width: 100%;

  border-collapse: collapse;
  thead {
    background: #f4f2f8;
    color: #2a2a2a;
    font-weight: 700;
    th {
      border-bottom: 1px solid #e8e8e8;
      vertical-align: middle;
      white-space: nowrap;
      padding: 10px;
    }
  }
  tr {
    td {
      text-align: center;
      padding: 10px;
      border-bottom: 1px solid #e8e8e8;
      white-space: nowrap;
    }
  }
}
</style>
